package com.mall.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.common.Constant;
import com.mall.common.Result;
import com.mall.exception.MallExceptionEnum;
import com.mall.model.po.User;
import org.springframework.http.HttpRequest;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AdminFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json;charset=utf-8");
//        获取用户信息
        User currentUser=(User) request.getSession().getAttribute(Constant.User.CURRENT_USER);
//        jackson转换json数据
        ObjectMapper objectMapper =new ObjectMapper();
//        判断当前登录用户为空
        if (currentUser==null){
            String result = objectMapper.writeValueAsString(Result.error(MallExceptionEnum.NEED_LOGIN));
            response.getWriter().write(result);
            return;
        }
//        判断当前用户是否为管理员
        if (currentUser.getRole().equals(Constant.User.IS_ADMIN)){
            filterChain.doFilter(request,response);
        }else {
            String result = objectMapper.writeValueAsString(Result.error(MallExceptionEnum.NEED_ADMIN));
            response.getWriter().write(result);
            return;
        }
    }

}
